package com.guaniu.voip.ui.main;
 
import static com.guaniu.voip.sip.SipManager.CALL_CONNECTED;
import static com.guaniu.voip.sip.SipManager.CALL_CONNECTING;
import static com.guaniu.voip.sip.SipManager.CALL_DISCONNECTED;
import static com.guaniu.voip.sip.SipManager.SIP_CALL_INCOMING;
import static com.guaniu.voip.sip.SipManager.SIP_CALL_OUTGOING;
import static com.guaniu.voip.ui.login.LoginActivity.PERMISSIONS_REQUEST_CODE;
import static com.guaniu.voip.ui.login.LoginActivity.PERMISSIONS_REQUIRED;

import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.SystemClock;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Chronometer;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;

import com.guaniu.voip.BaseActivity;
import com.guaniu.voip.MyApplication;
import com.guaniu.voip.R;
import com.guaniu.voip.sip.CALL_TYPE;
import com.guaniu.voip.sip.Constant;
import com.guaniu.voip.sip.INetworkManager;
import com.guaniu.voip.sip.Ring;
import com.guaniu.voip.sip.SipManager;

import net.gotev.sipservice.BroadcastEventReceiver;
import net.gotev.sipservice.MediaState;
import net.gotev.sipservice.SipServiceCommand;

import org.pjsip.pjsua2.pjsip_inv_state;


public class AudioChatActivity extends BaseActivity implements OnClickListener, BroadcastEventReceiver.SipEventObserver, INetworkManager.NetworkCallback{

	private static final String TAG = "AudioChatActivity";

	public final static String CALL_NUMBER = "call_number";
	public final static String DEFAULT_CALL_NUMBER_VALUE = "4000";
	
	private ImageButton mSendVideo;
	private ImageButton mSwitchMute;
	private ImageButton mSetting;
	private ImageButton mHandsFree;
	private Chronometer mTimer;


	private KeyguardLock mKeyguardLock;
	private WakeLock mWakeLock;

    private String mCallNumber;
    private boolean mbMute = false;

    private Handler mHandler;
    private boolean mbWaitConnect = false;

	private int mCallType = Constant.CALL_TYPE_NORMAL;
	private int mediaType = Constant.MEDIA_TYPE_AUDIO;

	private int mCallID = 0;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_audio_chat);

		mHandler = new Handler();		
		getRemoteData();
		initView();
		initConfig();
		initViewByCallType(mCallType);
		ActivityCompat.requestPermissions(this, PERMISSIONS_REQUIRED, PERMISSIONS_REQUEST_CODE);

		SipServiceCommand.getCallStatus(this, SipManager.getInstance().getAccount(), mCallID);

		//BroadcastEventReceiver.getBroadcastEventReceiver().registerEventObserverInner(this, this);
	}
	
	private void getRemoteData(){
        Intent intent = getIntent(); 
        mCallType = intent.getIntExtra(Constant.ID_CALL_TYPE, Constant.CALL_TYPE_NORMAL);
		mCallNumber = intent.getStringExtra(Constant.CALL_NUMBER);
		mCallID = intent.getIntExtra(Constant.SESSION_ID, 0);
//        mediaType = intent.getIntExtra(Constant.MEDIA_TYPE, Constant.MEDIA_TYPE_AUDIO);
		if (SipManager.getInstance().isOutGoingVideo()){
			mediaType = Constant.MEDIA_TYPE_VIDEO;
		}else{
			mediaType = Constant.MEDIA_TYPE_AUDIO;
		}
	}
	
	private void initView(){
		mSetting						= (ImageButton) findViewById(R.id.setting);
		mHandsFree					= (ImageButton) findViewById(R.id.hands_free);
		mSendVideo 					= (ImageButton) findViewById(R.id.send_video);
		mSwitchMute					= (ImageButton) findViewById(R.id.mute);
		mTimer 						= (Chronometer)this.findViewById(R.id.chronometer);

		if (mCallNumber != null){ 
			Log.d(TAG, "mCallNumber:"+mCallNumber); 
		}else{
			Log.d(TAG, "mCallNumber is null");
		}

		mSendVideo.setOnClickListener(this);
		mSetting.setOnClickListener(this);
		mSwitchMute.setOnClickListener(this);
		mHandsFree.setOnClickListener(this);

		final KeyguardManager keyguardManager = MyApplication.getKeyguardManager();
		if(keyguardManager != null){
			if(mKeyguardLock == null){
				mKeyguardLock = keyguardManager.newKeyguardLock(TAG);
			}
		}
	}

	private void initConfig(){
	}


	private void initViewByCallType(int callType){
		if(callType == Constant.CALL_TYPE_NORMAL){
			ready4AudioCall();
		}else{
			ready4Meeting();
		}
	}

	private void ready4AudioCall(){
		mTimer.setBase(SystemClock.elapsedRealtime());
		mTimer.start();
	}

	private void ready4Meeting(){
		mSendVideo.setBackgroundResource(R.drawable.icon_rec);
	}

	private void startCall(){
        mTimer.start();
	}

	private void acquireWakeLock(){
		PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
		mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, this.getClass().getCanonicalName());
		mWakeLock.acquire();
	}

	private void releaseWakeLock() {
		if (mWakeLock !=null&& mWakeLock.isHeld()) {
			mWakeLock.release();
			mWakeLock =null;
		}
	}

	private void changeButtonStatus(final boolean isSend) {
		// TODO Auto-generated method stub
		if (isSend){
			mSendVideo.setBackgroundResource(R.drawable.icon_stop_rec_press);
		}else{
			mSendVideo.setBackgroundResource(R.drawable.icon_rec);
		}
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}

	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK )
        {
        	finish();
            return true;
        }
        return false;
    }
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int vid = v.getId();
		switch(vid){
			case R.id.send_video:
				if(mCallType == Constant.CALL_TYPE_NORMAL){
					SipServiceCommand.hangUpCall(this, SipManager.getInstance().getAccount(), mCallID);

				}else{
				}
				break;
			case R.id.setting:
				break;
			case R.id.mute:
				mbMute = !mbMute;
				break;
			case R.id.hands_free:
				break;
		}
	}
	 
	private void endCall(){
		mTimer.setBase(SystemClock.elapsedRealtime());
		mTimer.stop();
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		acquireWakeLock();
		BroadcastEventReceiver.getBroadcastEventReceiver().registerEventObserverInner(this, this);

		super.onResume();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		// TODO Auto-generated method stub
//		getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		releaseWakeLock();
		BroadcastEventReceiver.getBroadcastEventReceiver().unRegisterEventObserverInner(this);
	}

	@Override
	protected void onStop() {
		super.onStop();
		Log.d(TAG,"onStop()");
		
		if(mKeyguardLock != null){
			mKeyguardLock.reenableKeyguard();
		}
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	
	INetworkManager.NETWORK_STATUS mNetWorkStatus = INetworkManager.NETWORK_STATUS.NETWORK_STATUS_INIT;
	@Override
	public void networkStatus(INetworkManager.NETWORK_STATUS status) {
		// TODO Auto-generated method stub

		Log.d(TAG, "networkStatus:"+status);

		this.runOnUiThread(new Runnable(){

			@Override
			public void run() { 
				updateNetWorkStatus();
			}});
	}

	private void updateNetWorkStatus(){
		switch(mNetWorkStatus){
			case NETWORK_STATUS_CONNECTED:
				break;
			case NETWORK_STATUS_CONNECTED_3G:
			{ 
				Toast.makeText(this, getString(R.string.call_network_3G_TIP), 3000).show();
			}
				break;
			case NETWORK_STATUS_CONNECTED_4G:
			{ 
				Toast.makeText(this, getString(R.string.call_network_4G_TIP), 3000).show();
			}
				break;
			case NETWORK_STATUS_CONNECTED_BUT_NO_NET:
			{ 
				Toast.makeText(this, getString(R.string.network_delay_100_300_audio), 3000).show(); 
			}
				break;
			case NETWORK_STATUS_DISCONNECTED:
			{ 
			}
				break;
		default:
			break;
		}
	}

	public void onSessionStateChange(int states) {
		// TODO Auto-generated method stub
		Log.i(TAG, ">>>>states:"+states);
		switch(states){
			case CALL_CONNECTING:
				break;
			case CALL_CONNECTED:
				if (mbWaitConnect){
					stopProgressDialog();
					mHandler.removeCallbacks(waitConnectedTimeout);
					mbWaitConnect = false;
					Toast.makeText(getApplicationContext(), getString(R.string.call_no_network_incall_reconnect_success), 3000).show(); 
				}
				changeButtonStatus(true);
				break;
			case CALL_DISCONNECTED:
				endCall();
				break;
			default:break;
		}
	}  
	
	private Runnable waitConnectedTimeout = new Runnable(){

		@Override
		public void run() {
			// TODO Auto-generated method stub
			if (!mbWaitConnect){
				Log.d(TAG, "waitConnectedTimeout mbWaitConnect set false, no need check");
				return;
			}
			stopProgressDialog();
			
			if (mCallNumber == null){				
				return;
			}

		}};
		
	private void startProgressDialog(){
		showError(getString((R.string.call_no_network_incall)));
	}  
	      
	private void stopProgressDialog(){   
		try{
		}catch(Exception ex){
			Log.d(TAG, "ex:"+ex.getMessage());
		}
	}

	@Override
	public void networkDelayStatus(INetworkManager.NETWORK_DELAY_STATUS status) {

	}

	@Override
	public void notifyRegState(String account, int code, String reason, long expiration) {
		if (code != 200){

			SipManager.getInstance().setCallStatus(CALL_DISCONNECTED);
			finish();
		}
	}

	@Override
	public void notifyIncomingCall(String accountID, int callID, String displayName, String remoteUri, boolean isVideo) {

	}

	@Override
	public void notifyCallState(String accountID, int callID, int callStateCode, int callStatusCode, long connectTimestamp) {
		if (pjsip_inv_state.PJSIP_INV_STATE_CALLING==callStateCode) {
		} else if (pjsip_inv_state.PJSIP_INV_STATE_INCOMING==callStateCode) {
		} else if (pjsip_inv_state.PJSIP_INV_STATE_EARLY==callStateCode) {
			//响铃
		} else if (pjsip_inv_state.PJSIP_INV_STATE_CONNECTING==callStateCode) {
			//连接中
		} else if (pjsip_inv_state.PJSIP_INV_STATE_CONFIRMED==callStateCode) {
			//连接成功
			SipManager.getInstance().setCallStatus(CALL_CONNECTED);

		} else if (pjsip_inv_state.PJSIP_INV_STATE_DISCONNECTED==callStateCode) {
			SipManager.getInstance().setCallStatus(CALL_DISCONNECTED);
			if (AudioChatActivity.this.isFinishing()){
				return;
			}
			finish();
		} else if (pjsip_inv_state.PJSIP_INV_STATE_NULL==callStateCode) {
			//未知错误

		}
	}

	@Override
	public void notifyCallMediaState(String accountID, int callID, MediaState stateType, boolean stateValue) {

	}

	@Override
	public void notifyChangeNetwork() {

	}
}
